<!--
 * @Descripttion: 供应商详情
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-07 13:55:37
 -->
<template>
  <div class="app-container">
    <el-card shadow="never" class="oper-btn-card">
      <div class="clearfix">
        <div class="fl">
          <el-button type="primary" :loading="btnLoading.save" @click="btnSave">保 存</el-button>
          <el-button
            v-if="oper === 'add'"
            type="primary"
            plain
            :loading="btnLoading.save"
            @click="btnSave('add')"
          >保存并新增</el-button>
          <el-button type="default" @click="btnCancle">取 消</el-button>
        </div>
        <div class="fr">
          <el-button type="default" @click="btnJump2list">供应商列表</el-button>
        </div>
      </div>
    </el-card>
    <el-container class="margin-t2">
      <el-aside width="200px" class="border-gay">
        <cate-tree
          ref="cateTree"
          :save-fun="saveCatData"
          :del-fun="delCatData"
          :list-data-fun="listCateData"
          title="分类 : "
          @node-click="handleNodeClick"
        />
      </el-aside>
      <el-main class="noPadding">
        <el-card shadow="never" class="oper-btn-card">
          <div slot="header">所属分类: 供应商分类 >  {{ currentCatNode.name }}</div>
          <el-form ref="customForm" :model="dataObj" :rules="rules" label-width="120px">
            <div style="width:600px;">
              <el-form-item label="编号:" prop="code">
                <el-input v-model="dataObj.code" />
              </el-form-item>
              <el-form-item label="名称:" prop="name">
                <el-input v-model="dataObj.name" style="width:300px;" />
                <el-checkbox v-model="dataObj.isDefault" true-label="1" false-label="0">是否默认供应商</el-checkbox>
              </el-form-item>
              <el-form-item label="单位电话:" prop="companyTel">
                <el-input v-model="dataObj.companyTel" />
              </el-form-item>
              <el-form-item label="联系人:">
                <el-input v-model="dataObj.contacter" />
              </el-form-item>
              <el-form-item label="联系电话:" prop="phone">
                <el-input v-model="dataObj.phone" />
              </el-form-item>
              <el-form-item label="联系地址:">
                <el-input v-model="dataObj.address" type="textarea" />
              </el-form-item>
              <el-form-item label="期初欠款:" prop="originDebt">
                <el-input-number v-model="dataObj.originDebt" />
              </el-form-item>
            </div>
            <h3 @click="btnIsShowMore">更多信息 <i class="el-icon-arrow-down" /></h3>
            <el-divider />
            <div v-if="isShowMore" class="paddingT20" style="width:600px;">
              <el-form-item label="微信号:">
                <el-input v-model="dataObj.wechat" />
              </el-form-item>
              <el-form-item label="传真:">
                <el-input v-model="dataObj.tax" />
              </el-form-item>
              <el-form-item label="邮箱:">
                <el-input v-model="dataObj.email" />
              </el-form-item>
              <el-form-item label="邮编:">
                <el-input v-model="dataObj.postal" />
              </el-form-item>
              <el-form-item label="QQ:">
                <el-input v-model="dataObj.qq" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="dataObj.remarks"
                  :auto-size="true"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
              <el-form-item v-if="false" label="关联客户:">
                <el-button type="primary" @click="btnRelation">关联客户</el-button>
                <el-button @click="btnCancleRelation">取消关联</el-button>
                <p class="font12">当供应商同时又是您的客户，建议您关联到该客户。关联后可以灵活地互相抵消欠款。（一个供应商只能与一个客户关联）</p>
                <el-table
                  v-if="relationTable.length"
                  :data="relationTable"
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    prop="code"
                    label="客户编号"
                    width="180"
                  />
                  <el-table-column
                    prop="name"
                    label="客户名称"
                  />
                </el-table>
              </el-form-item>
            </div>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
    <el-dialog
      title="选择客户"
      width="90%"
      height="90%"
      :visible.sync="isShowCustomerList"
      destroy-on-close
      append-to-body
    >
      <CustomerList v-if="isShowCustomerList" oper="select" @on-select="onCustomerSelect" />
    </el-dialog>
  </div>
</template>

<script>
import { getdataById, saveData as saveSupplierData, genBillcode } from '@/api/bsd/supplier/supplier'
import { saveData as saveCatData,
  delData as delCatData, listData as listCateData } from '@/api/bsd/supplier/supplier-cat.js'
import { oftenuse } from '@/libs/mixins'
import { isTelOrPhone } from '@/utils/validate'
import CateTree from '@/views/components/Category'
import CustomerList from '@/views/bsd/customer/list'
import clonedeep from 'clonedeep'

export default {
  name: 'SupplierAdd',
  components: { CateTree, CustomerList },
  mixins: [oftenuse],
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      saveCatData: saveCatData,
      delCatData: delCatData,
      listCateData: listCateData,
      isShowCustomerList: false,
      relationTable: [],
      defaultDataObj: { isPublic: '0', originDebt: 0 },
      catComp: null,
      isShowMore: true,
      rules: {
        code: [
          { required: true, message: '请输入客户编号', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入客户名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        companyTel: [
          { validator: isTelOrPhone, trigger: 'blur' }
        ],
        phone: [
          { validator: isTelOrPhone, trigger: 'blur' }
        ],
        amountPayable: [
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    catData() {
      if (!this.catComp) return []
      return this.catComp.cateData || []
    },
    // 编辑的时候用
    currentCatData() {
      return { id: this.dataObj.catId }
    },
    currentCatNode() {
      if (!this.catComp) return {}
      return this.catComp.currentNode || {}
    },
    oper() {
      if (this.id) return 'update'
      return 'add'
    }
  },
  watch: {
    'catData': {
      handler(data) {
        const catData = data
        const currentCatData = this.currentCatData
        this.handleCatTreeCurrentData(catData, currentCatData)
      },
      immediate: true
    },
    'dataObj': {
      handler(data) {
        const catData = this.catData
        const currentCatData = this.currentCatData
        this.handleCatTreeCurrentData(catData, currentCatData)
      }
    }
  },
  created() {
    this.initData()
  },
  destroyed() {
  },
  mounted() {
    const comp = this.$refs.cateTree
    this.catComp = comp
  },
  methods: {
    btnJump2list() {
      this.jump2list()
    },
    btnCancle() {
      this.jump2list()
    },
    btnRelation() {
      this.isShowCustomerList = true
    },
    btnCancleRelation() {
      this.relationTable = []
      this.$set(this.dataObj, 'customerId', null)
    },
    btnIsShowMore() {
      this.isShowMore = !this.isShowMore
    },
    btnSave(oper) {
      this.handleValid('customForm').then(() => {
        if (!this.currentCatNode.id) return this.$message.error('请选择分类！')
        const params = this.dataObj
        this.setBtnLoading('save', true)
        this.saveData(params).then((res) => {
          this.setBtnLoading('save', false)
          if (res.data.flag) {
            if (oper === 'add') {
              this.resetData()
            } else {
              this.jump2list()
            }
          }
        }).catch(_ => {
          this.setBtnLoading('save', false)
        })
      })
    },
    handleNodeClick(data) {
      const { id } = data
      this.$set(this.dataObj, 'catId', id)
    },
    jump2list() {
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'SupplierList',
        params: { refresh: true }
      })
    },
    /**
     * 获取传递的值
     */
    getPassOnData() {
      return this.$route.query
    },
    resetData() {
      this.initAddData()
    },
    getGoodDataById(data) {
      getdataById(data).then(res => {
        if (res.data.flag) {
          const resData = res.data.data
          const obj = {
            code: resData.customerCode,
            name: resData.customerName
          }
          this.relationTable.push(obj)
          this.dataObj = resData
        }
      })
    },
    handleCatTreeCurrentData(catData, currentCat) {
      const comp = this.catComp
      if (!comp) return
      if (this.oper === 'add') {
        const defaultNode = catData.find(item => { return item.id !== '0' && item.isDefault === '1' })
        if (defaultNode) {
          comp.setCurrentNode(defaultNode)
          this.$set(this.dataObj, 'catId', defaultNode.id)
        }
      } else {
        const currentNode = catData.find(item => { return item.id === currentCat.id })
        const targetNode = currentNode
        targetNode && comp.setCurrentNode(targetNode)
      }
    },
    setGoodType(data) {
      this.$set(this.dataObj, 'typeId', data.id)
      this.$set(this.dataObj, 'typeName', data.name)
    },
    setGoodUnit(data) {
      this.$set(this.dataObj, 'unit', data.name)
    },
    handleCode() {
      genBillcode().then(res => {
        if (!res.data.flag) return this.$message.error('获取编号失败！')
        this.$set(this.dataObj, 'code', res.data.data)
      })
    },
    initUpdateData(id) {
      this.getGoodDataById(id)
    },
    initAddData() {
      this.dataObj = clonedeep(this.defaultDataObj)
      this.handleCode()
    },
    initData() {
      const id = this.id
      if (id) {
        this.initUpdateData(id)
      } else {
        this.initAddData()
      }
    },
    saveData(params) {
      params.cat = this.currentCatNode.id
      return new Promise((resolve, reject) => {
        saveSupplierData(params).then(res => {
          resolve(res)
          this.$message[res.data.flag ? 'success' : 'error'](res.data.message)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // on
    onCustomerSelect(data) {
      const obj = { code: data.code, name: data.name }
      this.relationTable = [obj]
      this.$set(this.dataObj, 'customerId', data.id)
      this.isShowCustomerList = false
    }
  }
}
</script>

<style scoped>
.el-divider--horizontal{
  margin: 5px 0;
}
</style>
